package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.properties.JwtProperties;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import com.sky.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private JwtProperties jwtProperties;
    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对

        //把密码进行md5加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    @Override
    public void addEmployee(EmployeeDTO employeeDTO) {
        String password = PasswordConstant.DEFAULT_PASSWORD;
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //对象赋值，可以用更简单的方法：BeanUtil的对象属性拷贝
        //** 前提：两个实体的对象名称一致
//        Employee employee = new Employee();
//        BeanUtils.copyProperties(employeeDTO, employee);
        Employee employee =  Employee.builder()
                .name(employeeDTO.getName())
                .username(employeeDTO.getUsername())
                .password(password)
                .phone(employeeDTO.getPhone())
                .sex(employeeDTO.getSex())
                .idNumber(employeeDTO.getIdNumber())
                .status(StatusConstant.ENABLE)
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .createUser(BaseContext.getCurrentId())
                .updateUser(BaseContext.getCurrentId())
                .build();
//  使用JWT也可以获取用户id：拿到header请求头，
//        String token = request.getHeader("token");
//        System.out.println("***************token:"+token);
//        Map claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
//        Long userId= Long.valueOf(claims.get("empId").toString());
//        System.out.println("**************userid:"+userId);
          employeeMapper.addEmployee(employee);



    }

    @Override
    public PageResult getPage(EmployeePageQueryDTO employeePageQueryDTO) {
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
        Page<Employee> page = employeeMapper.getPage(employeePageQueryDTO.getName(),
                employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
        PageResult pageResult = new PageResult(page.getTotal(),page.getResult());
        return pageResult;
    }

    @Override
    public void updateStatus(Integer status,long id) {
        Employee employee = new Employee();
        employee.setStatus(status);
        employee.setId(id);
        employeeMapper.updateEmployee(employee);
    }

    @Override
    public void updateEmployee(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);
//        employee.setUpdateTime(LocalDateTime.now());
        employeeMapper.updateEmployee(employee);
    }

    @Override
    public Employee getEmployeeById(long id) {
        Employee employee = employeeMapper.getById(id);
        return employee;
    }

    @Override
    public void updatePassword(PasswordEditDTO passwordEditDTO) {
        //先验证密码是否正确
        String password = passwordEditDTO.getOldPassword();
        //把旧密码进行md5加密，再进行对比
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        Employee employee = employeeMapper.getById(BaseContext.getCurrentId());
        if(!password.equals(employee.getPassword())){
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }else{
            employee.setPassword(DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes()));
            employeeMapper.updateEmployee(employee);
        }
    }

//    @Override
//    public PageResult page(int page, int pageSize) {
//        int total = employeeMapper.getTotal();
//        int start = (page - 1) * pageSize;
//        List<Employee> employeeList = employeeMapper.getPage(start,pageSize);
//        PageResult pageResult = new PageResult(total,employeeList);
//        return pageResult;
//    }
//
//    @Override
//    public PageResult getEmployeeByName(String name,int page, int pageSize) {
//        int total = employeeMapper.getTotalByName(name);
//        int start = (page - 1) * pageSize;
//        List<Employee> employee = employeeMapper.getByName(name,start,pageSize);
//        PageResult pageResult = new PageResult(total,employee);
//        return pageResult;
//    }

}
